//
//  DR_TabBarVC.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/10.
//

import UIKit
import SnapKit

enum TabbarType: CaseIterable {
    case home
    case collect
    case folder
    case setting
    
    var imageName: String {
        switch self {
        case .home:
            return "tabbar_home"
        case .collect:
            return "tabbar_collect"
        case .folder:
            return "tabbar_folder"
        case .setting:
            return "tabbar_setting"
        }
    }
    
    var selImageName: String {
        return "\(imageName)_sel"
    }

    var controller: UIViewController {
        switch self {
        case .home:
            return DR_HomeVC()
        case .collect:
            return DR_CollectVC()
        case .folder:
            return DR_FolderVC()
        case .setting:
            return DR_SettingVC()
        }
    }
    
    /// 创建导航控制器
    func createNavigationController() -> UINavigationController {
        let vc = controller
        let nav = UINavigationController(rootViewController: vc)
        nav.tabBarItem = UITabBarItem(
            title: nil,
            image: UIImage(named: imageName),
            selectedImage: UIImage(named: selImageName)
        )
        nav.tabBarItem.imageInsets = UIEdgeInsets(top: 15, left: 0, bottom: -15, right: 0)
        return nav
    }
}

class DR_TabBarVC: UITabBarController {

    private var addButton: UIButton!
    private var addButtonConstraints: [NSLayoutConstraint] = []
    private var isUpdatingButton = false // 防止重复更新
    private var isActionSheetShowing = false // 标记弹窗是否正在显示

    override func viewDidLoad() {
        super.viewDidLoad()

        self.delegate = self
        setupTabBar()
        setupViewControllers()
        setupAddButton()
    }
    
    private func setupNavigationObservers() {
        // 监听所有 NavigationController 的 push/pop 事件
        for viewController in viewControllers ?? [] {
            if let navController = viewController as? UINavigationController {
                // 设置 NavigationController 的 delegate 来监听 push/pop
                // 如果已经有 delegate，我们需要保存原来的，或者直接使用我们的
                navController.delegate = self
            }
        }
    }
    
    private func setupTabBar() {
        // 创建自定义 TabBar
        let customTabBar = DR_CustomTabBar()
        self.setValue(customTabBar, forKey: "tabBar")
        
        // 设置 TabBar 外观
        tabBar.tintColor = UIColor(red: 0.2, green: 0.4, blue: 0.8, alpha: 1.0) // 蓝色选中色
        tabBar.unselectedItemTintColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1.0) // 灰色未选中色
        
        // 移除默认的阴影和边框
        tabBar.shadowImage = UIImage()
        
        // 移除背景色，让背景图片完全显示
        tabBar.backgroundColor = .clear
        
        // 使用背景图片
        if let bgImage = UIImage(named: "tab_bg") {
            // 如果图片需要适配不同屏幕宽度，使用 resizableImage
            // 根据图片设计，可能需要保护左右边缘和中间的凹陷部分
            // 如果图片已经设计为固定宽度，可以直接使用原图
            // 先尝试直接使用原图，如果显示不正确再调整
            tabBar.backgroundImage = bgImage
        }
        
        // 增加 TabBar 高度，为中间的添加按钮留出空间
        if #available(iOS 15.0, *) {
            let appearance = UITabBarAppearance()
            appearance.configureWithTransparentBackground()
            // 移除背景色
            appearance.backgroundColor = .clear
            // 使用背景图片
            if let bgImage = UIImage(named: "tab_bg") {
                appearance.backgroundImage = bgImage
            }
            tabBar.standardAppearance = appearance
            tabBar.scrollEdgeAppearance = appearance
        }
    }
    
    private func setupViewControllers() {
        var viewControllers: [UIViewController] = []
        
        // 使用 TabbarType 创建前两个 tab（Home, Collect）
        let leftTabs: [TabbarType] = [.home, .collect]
        for tabType in leftTabs {
            viewControllers.append(tabType.createNavigationController())
        }
        
        // 创建占位 ViewController（用于中间添加按钮的位置）
        let placeholderVC = UIViewController()
        placeholderVC.tabBarItem = UITabBarItem()
        placeholderVC.tabBarItem.isEnabled = false
        viewControllers.append(placeholderVC)
        
        // 使用 TabbarType 创建后两个 tab（Folder, Setting）
        let rightTabs: [TabbarType] = [.folder, .setting]
        for tabType in rightTabs {
            viewControllers.append(tabType.createNavigationController())
        }
        
        self.viewControllers = viewControllers
        self.selectedIndex = 0
    }
    
    private func setupAddButton() {
        // 创建中间的添加按钮
        addButton = UIButton(type: .custom)
        let buttonSize: CGFloat = 58
        
        // 设置按钮图片
        if let addImage = UIImage(named: "tabbar_add") {
            addButton.setImage(addImage, for: .normal)
        }
        
        addButton.addTarget(self, action: #selector(addButtonTapped), for: .touchUpInside)
        
        // 将按钮添加到主视图，而不是 TabBar，这样可以确保完全显示
        view.addSubview(addButton)
        
        // 设置按钮位置（在 TabBar 中间，嵌入到背景图片的凹陷中）
        // 根据 tab_bg 图片的凹陷设计，按钮应该稍微嵌入到 TabBar 中
        addButton.translatesAutoresizingMaskIntoConstraints = false
        
        // 保存约束引用，以便后续更新
        // 使用相对于 view 的约束，这样即使 TabBar 隐藏，约束也不会失效
        // 初始时使用一个临时值，稍后会在 viewDidLayoutSubviews 中更新
        let tabBarHeight = tabBar.frame.height > 0 ? tabBar.frame.height : 83 // 默认 TabBar 高度
        let bottomConstraint = addButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -tabBarHeight + 85) // 从 48 改为 40，向下移动
        
        addButtonConstraints = [
            addButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            bottomConstraint,
            addButton.widthAnchor.constraint(equalToConstant: buttonSize),
            addButton.heightAnchor.constraint(equalToConstant: buttonSize)
        ]
        NSLayoutConstraint.activate(addButtonConstraints)
    }
    
    @objc private func addButtonTapped() {
        // 显示添加操作弹窗
        showAddActionSheet()
    }
    
    private func showAddActionSheet() {
        // 标记弹窗正在显示
        isActionSheetShowing = true
        
        // 隐藏添加按钮
        addButton?.isHidden = true
        
        let actionSheet = DR_AddActionSheet()
        
        actionSheet.onFileImportTapped = { [weak self] in
            self?.handleFileImportTapped()
        }
        
        actionSheet.onDismiss = { [weak self] in
            // 标记弹窗已关闭
            self?.isActionSheetShowing = false
            // 显示添加按钮
            self?.addButton?.isHidden = false
        }
        
        actionSheet.show(in: view)
        
        // 延迟确保弹窗在最上层（在布局完成后）
        DispatchQueue.main.async { [weak self] in
            self?.view.bringSubviewToFront(actionSheet)
        }
    }
    
    private func handleFileImportTapped() {
        guard let topViewController = getTopViewController() else {
            print("⚠️ [DR_TabBarVC] 无法获取顶层 ViewController")
            return
        }
        
        DR_FileImportTool.shared.presentDocumentPicker(from: topViewController) { [weak self] fileURL in
            print("✅ [DR_TabBarVC] 文件导入成功: \(fileURL.path)")
            
            // 显示成功提示并刷新文件列表
            DispatchQueue.main.async {
                let fileName = fileURL.lastPathComponent
                
                // 发送通知刷新文件列表
                NotificationCenter.default.post(name: NSNotification.Name("FileImported"), object: nil)
                
                // 显示成功提示（如果当前 ViewController 支持 Toast）
                if let homeVC = topViewController as? DR_HomeVC {
                    homeVC.view.makeToast("文件导入成功: \(fileName)", duration: 2.0, position: .center)
                }
            }
        }
    }
    
    // MARK: - 获取顶层 ViewController
    private func getTopViewController() -> UIViewController? {
        guard let window = UIApplication.shared.keyWindow,
              let rootViewController = window.rootViewController else {
            return nil
        }
        
        var topViewController = rootViewController
        while let presentedViewController = topViewController.presentedViewController {
            topViewController = presentedViewController
        }
        
        if let tabBarController = topViewController as? UITabBarController,
           let selectedViewController = tabBarController.selectedViewController {
            topViewController = selectedViewController
        }
        
        if let navigationController = topViewController as? UINavigationController,
           let visibleViewController = navigationController.visibleViewController {
            topViewController = visibleViewController
        }
        
        return topViewController
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 当视图即将显示时，更新按钮状态
        updateAddButtonVisibility()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 在视图显示后设置 NavigationController 的 delegate
        setupNavigationObservers()
        // 当视图显示后，再次更新按钮状态，确保布局正确
        DispatchQueue.main.async { [weak self] in
            self?.updateAddButtonVisibility()
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        // 如果弹窗正在显示，不处理 addButton
        guard !isActionSheetShowing else { return }
        
        // 确保添加按钮始终在最上层
        if let addButton = addButton {
            view.bringSubviewToFront(addButton)
            
            // 更新按钮状态（在布局完成后，TabBar 的 frame 和状态会更准确）
            updateAddButtonVisibility()
            
            // 更新按钮的底部约束，确保位置正确
            if !addButton.isHidden && tabBar.frame.height > 0 {
                for constraint in addButtonConstraints {
                    if constraint.firstAttribute == .bottom || constraint.secondAttribute == .bottom {
                        constraint.constant = -tabBar.frame.height + 85 // 从 48 改为 40，向下移动
                        break
                    }
                }
            }
        }
    }
    
    private func updateAddButtonVisibility() {
        // 如果弹窗正在显示，不更新按钮可见性
        guard !isActionSheetShowing else { return }
        
        // 防止重复更新导致崩溃
        guard !isUpdatingButton, let addButton = addButton else { return }
        isUpdatingButton = true
        defer { isUpdatingButton = false }
        
        // 根据 TabBar 的可见性来显示/隐藏添加按钮
        // 当 TabBar 隐藏时（比如 push 到其他页面），也隐藏添加按钮
        var hidesTabBar = false
        
        // 方法1: 检查当前 topViewController 是否隐藏了 TabBar
        if let navController = selectedViewController as? UINavigationController,
           let topViewController = navController.topViewController {
            // 如果 topViewController 设置了 hidesBottomBarWhenPushed，TabBar 会被隐藏
            hidesTabBar = topViewController.hidesBottomBarWhenPushed
        }
        
        // 方法2: 检查 TabBar 的实际可见状态（作为双重验证）
        let tabBarActuallyVisible = !tabBar.isHidden && 
                                   tabBar.alpha > 0 &&
                                   tabBar.frame.height > 0 &&
                                   tabBar.frame.width > 0 &&
                                   tabBar.frame.maxY <= view.bounds.maxY &&
                                   tabBar.frame.minY >= view.bounds.minY
        
        // 两个条件都要满足才显示按钮：没有隐藏 TabBar 且 TabBar 实际可见
        let isTabBarVisible = !hidesTabBar && tabBarActuallyVisible
        
        // 只在状态改变时更新，避免不必要的操作
        let shouldBeHidden = !isTabBarVisible
        if addButton.isHidden != shouldBeHidden {
            addButton.isHidden = shouldBeHidden
            
            // 如果 TabBar 可见，更新约束位置
            if isTabBarVisible && !addButtonConstraints.isEmpty && tabBar.frame.height > 0 {
                // 更新底部约束，使其相对于 TabBar 位置
                // 找到底部约束并更新
                for constraint in addButtonConstraints {
                    if constraint.firstAttribute == .bottom || constraint.secondAttribute == .bottom {
                        constraint.constant = -tabBar.frame.height + 85 // 从 48 改为 40，向下移动
                        break
                    }
                }
            }
        }
    }
    
}

// MARK: - UITabBarControllerDelegate
extension DR_TabBarVC: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        // 防止选择中间的占位 ViewController（索引为2）
        if let index = viewControllers?.firstIndex(of: viewController), index == 2 {
            return false
        }
        return true
    }
    
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        // 当切换 Tab 时，延迟更新添加按钮的显示状态，确保布局已完成
        DispatchQueue.main.async { [weak self] in
            self?.updateAddButtonVisibility()
        }
    }
}

// MARK: - UINavigationControllerDelegate
extension DR_TabBarVC: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        // 当 NavigationController 即将显示新的 ViewController 时，更新按钮状态
        DispatchQueue.main.async { [weak self] in
            self?.updateAddButtonVisibility()
        }
    }
    
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        // 当 NavigationController 显示完新的 ViewController 后，再次更新按钮状态
        DispatchQueue.main.async { [weak self] in
            self?.updateAddButtonVisibility()
        }
    }
}

// 自定义 TabBar 类，用于添加圆角效果和增加高度
class DR_CustomTabBar: UITabBar {
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        // 增加 TabBar 高度，为中间的添加按钮留出空间
        var sizeThatFits = super.sizeThatFits(size)
        let additionalHeight: CGFloat = 20 // 增加额外高度，确保按钮完全显示
        sizeThatFits.height += additionalHeight
        return sizeThatFits
    }
}
